LEARNING OBJECTIVES

IN THIS TUTORIAL YOU WILL LEARN:
1.) How to apply basic plotting functions to new data
2.) How to add color, themes, and other aesthetics
3.) How to panel plots w/ patchwork


Additional Tutorials and Resources for graphs in ggplot

Basics of ggplot

Colors with ggsci

Many plots, 1 page w/ Patchwork


1.) Load any packages we may need

knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ ggplot2 3.3.5     ✓ purrr   0.3.4
## ✓ tibble  3.1.2     ✓ dplyr   1.0.7
## ✓ tidyr   1.1.0     ✓ stringr 1.4.0
## ✓ readr   1.3.1     ✓ forcats 0.5.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(ggsci) #this package allows us to EASILY add good color schemes to plot
library(patchwork) #this package is used to panel many plots onto 1 page 

2.) ggplot basics

Introduction

ggplot2 is the preferred graphics package for most R users. It allows users to build a graph piece by piece from your own data through mapping of aesthetics. It is much easier to make pretty (publication and presentation quality) plots with ggplot2 than it is with the base plot function in R. If you prefer base plot() that is ok. You can use whatever you’d like but when we talk about graphs we will be using the language of ggplot.

Attached here are the Tidyverse Cheat Sheets for ggplot2


ggplot()

The ggplot() function is the base of the ggplot2 package. Using it creates the space that we use to build a graph. If we run just the ggplot() function we will get a gray rectangle. This is the space (and background) of our plot!

ggplot()

To build a plot on the background, we must add to the ggplot call. First, we need to tell it what data to use. Next, we need to tell it where in the data frame to pull data from to build the axes and data points. The part of the ggplot() function we use to build a graph is called aes() or aesthetics.

Here is an example using penguins: I am telling ggplot that the data we are using is ‘penguins’ and then defining the x and y axis in the aes() call with column names from penguins

penguins <- read.csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-07-28/penguins.csv')
head(penguins)
species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g sex year
Adelie Torgersen 39.1 18.7 181 3750 male 2007
Adelie Torgersen 39.5 17.4 186 3800 female 2007
Adelie Torgersen 40.3 18.0 195 3250 female 2007
Adelie Torgersen NA NA NA NA NA 2007
Adelie Torgersen 36.7 19.3 193 3450 female 2007
Adelie Torgersen 39.3 20.6 190 3650 male 2007
ggplot(data=penguins, aes(x=species, y= bill_length_mm)) 

Like anything in R, we can give our plot a name and call it later

plot1<-ggplot(data=penguins, aes(x=species, y= bill_length_mm)) 

plot1

This is incredibly useful in ggplot as we can essentially add pieces to make a more complete graph

plot1+
  geom_boxplot()+
  geom_point()+
  theme_bw()
## Warning: Removed 2 rows containing non-finite values (stat_boxplot).
## Warning: Removed 2 rows containing missing values (geom_point).

Before we get too excited about making perfect graphs, let’s take a look at the types of graphs we have available to us…


histogram

Histograms are used to explore the frequency distribution of a single variable. We can check for normality (a bell curve) using this feature. We can also look for means, skewed data, and other trends.

ggplot(data=penguins, aes(bill_length_mm))+
  geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 2 rows containing non-finite values (stat_bin).

Within geom_histogram we can use bin_width to change the width of our x-axis groupings.

ggplot(data=penguins, aes(bill_length_mm))+
  geom_histogram(binwidth=5)
## Warning: Removed 2 rows containing non-finite values (stat_bin).

boxplot

A boxplot is a really useful plot to assess median and range of data. It can also identify outliers! The defaults for a boxplot in ggplot produce a median and interquartile range (IQR). The 1st quartile is the bottom of the box and the 3rd quartile is the top. The whiskers show the spread of the data where the ends of the whiskers represent the data points that are the furthest from the median in either direction. Notably, if a data point is 1.5 * IQR from the box (either the 1st or 3rd quartile) it is an outlier. Outliers are excluded from whiskers and are presented as points. There

Here’s an example

ggplot(data=penguins, aes(x=species, y= bill_length_mm)) +
  geom_boxplot()
## Warning: Removed 2 rows containing non-finite values (stat_boxplot).

We can use geom_violin to combine boxplot with a density plot (similar to a histogram) Here we can see the distribution of values within bill length by species.

ggplot(data=penguins, aes(x=species, y= bill_length_mm)) +
  #geom_boxplot()+
  geom_violin()
## Warning: Removed 2 rows containing non-finite values (stat_ydensity).


bar graph

We can make bar graphs in ggplot using geom_bar(). There are some tricks to getting bar graphs to work exactly right, which I will try to detail below. NOTE Bar graphs are very rarely useful. If we want to show means, why not just use points + error bars? What does the bar actually represent? There aren’t that many cases where we really need bar graphs. There are exceptions, like when we have a population and we want to see the demographics of that population by count or percentage (see example below)

Here is a simple bar chart.

ggplot(data=penguins, aes(species)) +
  geom_bar()

Here is a more elaborate boxplot that shows sex breakdown by species! Note that we use an aes() call within geom_bar to define a fill. That means fill by species, or add a color for each species.

ggplot(data=penguins, aes(sex)) +
  geom_bar(aes(fill=species))

And here is that same plot with the bars unstacked. Instead of stacking, we have used “dodged” each color to be its own bar.

ggplot(data=penguins, aes(sex)) +
  geom_bar(aes(fill=species), position= position_dodge())


line graph

A line graph can be extremely useful, especially if we are looking at time series data or rates!

Here is an example of CO2 uptake vs concentration in plants. Each color represents a different plant.

head(CO2)
Plant Type Treatment conc uptake
Qn1 Quebec nonchilled 95 16.0
Qn1 Quebec nonchilled 175 30.4
Qn1 Quebec nonchilled 250 34.8
Qn1 Quebec nonchilled 350 37.2
Qn1 Quebec nonchilled 500 35.3
Qn1 Quebec nonchilled 675 39.2
ggplot(data=CO2, aes(x=conc, y= uptake, color=Plant)) +
  geom_line()

We can change the aesthetics of the lines using color, linetype, size, etc. Here I am changing the linetype based on the plant species and increasing the size of ALL lines to 2. This is a good example of how aes() works. Anything within the aes() call is conditional. That means, I give it a name (such as a column or variable name) and it changes based on that column or variable. To change an aesthetic across all lines, points, etc, I just put the code outside of the aes(). As I did for size. That makes the size of ALL lines = 2.

ggplot(data=CO2, aes(x=conc, y= uptake, color=Plant)) +
  geom_line(aes(linetype=Plant),size=2)


scatter plot

The scatter plot is probably the most commonly used graphical tool in ggplot. It is based on the geom_point() function

ggplot(data=penguins, aes(x=species, y= bill_length_mm)) +
  geom_point()
## Warning: Removed 2 rows containing missing values (geom_point).

Importantly, we can use the data= and aes() calls within geom_point() or any other geom instead of within ggplot() if needed. Why might this be important?

ggplot() +
  geom_point(data=penguins, aes(x=species, y= bill_length_mm))
## Warning: Removed 2 rows containing missing values (geom_point).

Sometimes we don’t want to plot all of our points on the same vertical line. If that is the case, we can use geom_jitter()

ggplot(data=penguins, aes(x=species, y= bill_length_mm)) +
  geom_jitter()
## Warning: Removed 2 rows containing missing values (geom_point).


Adding error bars

We often want to present means and error in our visualizations. This can be done through the use of geom_boxplot() or through combining geom_point() with geom_errorbar()

Here is an example of the later…

#First, we need to calculate a mean bill length for our penguins by species and sex
sumpens<- penguins %>%
  group_by(species, sex) %>%
  summarize(meanbill=mean(bill_length_mm), sd=sd(bill_length_mm), n=n(), se=sd/sqrt(n))%>%
  na.omit() #removes rows with NA values (a few rows would otherwise have NA in 'sex' due to sampling error in the field)
## `summarise()` has grouped output by 'species'. You can override using the `.groups` argument.
sumpens
species sex meanbill sd n se
Adelie female 37.25753 2.028883 73 0.2374628
Adelie male 40.39041 2.277131 73 0.2665180
Chinstrap female 46.57353 3.108669 34 0.5331324
Chinstrap male 51.09412 1.564558 34 0.2683196
Gentoo female 45.56379 2.051247 58 0.2693419
Gentoo male 49.47377 2.720594 61 0.3483364
# Now we can plot! 
ggplot(data=sumpens, aes(x=species, y=meanbill, color=sex))+
  geom_point()+
  geom_errorbar(data=sumpens, aes(x=species, ymin=meanbill-se, ymax=meanbill+se), width=0.2)

And if we want to be extra fancy (and rigorous), we can plot the raw data behind the mean+error This is considered a graphical best practice as we can see the mean, error, and the true spread of the data!

ggplot()+
  geom_jitter(data= penguins, aes(x=species, y=bill_length_mm, color=sex), alpha=0.5, width=0.2)+
  geom_point(data=sumpens, aes(x=species, y=meanbill, color=sex), size=3)+
  geom_errorbar(data=sumpens, aes(x=species, ymin=meanbill-se, ymax=meanbill+se), width=0.1)
## Warning: Removed 2 rows containing missing values (geom_point).


3.) Aesthetics

shapes

ggplot gives us options to change point shape using the aesethic option ‘shape’
We can either change shape based on a characterstic of the data (‘cyl’, for example), make all the shapes the same, or manually control shape

Below is a table of shape options:

ggplot shape options

Conditional Shape Change

ggplot(data=penguins, aes(x=species, y=bill_length_mm, color=island, shape=sex))+ 
  geom_jitter(size=2)+
  theme_classic()
## Warning: Removed 11 rows containing missing values (geom_point).

Change all shapes to triangles

ggplot(data=mtcars, aes(x=cyl, y=mpg, color=cyl))+
  geom_point(shape=17) #Here 'shape=' is inside the settings for geom_point. Note that it is outside the aes() function, as that applied aesethics conditionally)

#example 2, same w/ different syntax
ggplot()+
  geom_point(data=mtcars, aes(x=cyl, y=mpg, color=cyl), shape=17)

Manual shape changes

ggplot(data=penguins, aes(x=species, y=bill_length_mm, color=island, shape=sex))+ 
  geom_jitter(size=2)+
  theme_classic()+  
  scale_shape_manual(values=c(2,3,4)) #scale_shape_manual allows us to choose shapes for each group (cyl in this case). c stands for concatenate, as we've seen before
## Warning: Removed 11 rows containing missing values (geom_point).

Changing Size of points

Conditional Shape Change

ggplot(data=mtcars, aes(x=cyl, y=mpg, color=cyl, size=cyl))+ #note that we added 'size=' to our aes. 
  geom_point()

#note the warning message that using size for a discrete variable is not best practice. 
#Instead, let's use the size to five us an idea of hp (a 3rd variable)

ggplot(data=mtcars, aes(x=cyl, y=mpg, color=cyl, size=hp))+ #note that we added 'size=' to our aes. 
  geom_point()

Change size of all points (all points must be same size)

ggplot(data=mtcars, aes(x=cyl, y=mpg, color=cyl))+  
  geom_point(size=5) #as w/ shape, point needs to be outside the aes() here. 


colors

We can change colors conditionally or manually.

Conditional Color Change To change colors conditionally, we use color= or fill= within an aes() call.

Here I have changed the outline color (color=) for a series of boxplots based on species

ggplot(data=penguins, aes(x=species, y= bill_length_mm, color=species)) +
  geom_boxplot()
## Warning: Removed 2 rows containing non-finite values (stat_boxplot).

I can also change the fill of the boxplots

ggplot(data=penguins, aes(x=species, y= bill_length_mm, fill=species)) +
  geom_boxplot()
## Warning: Removed 2 rows containing non-finite values (stat_boxplot).

Manual Color Change We can also change colors manually by using one of many options within ggplot. scale_color_manual (or scale_fill_manual) is the easiest. We simply define colors we want to use by name or hexcode.

ggplot(data=penguins, aes(x=species, y= bill_length_mm)) +
  geom_boxplot(aes(fill=species))+
  scale_fill_manual(values=c('red', 'black', 'blue'))
## Warning: Removed 2 rows containing non-finite values (stat_boxplot).

Here’s a giant table of color options in ggplot

ggplot color options

You can also make your own color palette and apply that to your figure!

mypal<-c('dodgerblue', 'forestgreen', 'coral') # here I've made a 3 color palette

ggplot(data=penguins, aes(x=species, y= bill_length_mm)) +
  geom_boxplot(aes(fill=species))+
  scale_fill_manual(values=mypal)
## Warning: Removed 2 rows containing non-finite values (stat_boxplot).

You can use the package RColorBrewer to make palettes as well. I’ll let you explore that one on your own!

Finally, EASY and nice looking palettes with ggsci ggsci is a simple and neat package that allows us to use scientific journal color themes for our data (usually colorblind friendly and nice looking). we simply change our “scale_color_manual” to “scale_color_palname” where “palname” is one of many provided by ggsci. For example, we might use scale_color_aaas()

ggplot(data=penguins, aes(x=species, y= bill_length_mm)) +
  geom_boxplot(aes(fill=species))+
  scale_fill_aaas()
## Warning: Removed 2 rows containing non-finite values (stat_boxplot).


titles and axis labels

Titles and axis labels are easy to add and change in ggplot! We simply add another line to our code. NOTE you can also add a subtitle, caption, or change the legend title using labs!

ggplot(data=penguins, aes(x=species, y= bill_length_mm)) +
  geom_boxplot(aes(fill=species))+
  scale_fill_aaas()+
  labs(x = 'Species', y='Bill length (mm)', title='Penguin bill length by species', fill='Species') #here I change the x-axis and y-axis labels, add a title, and change the legend label (to capitalize the 'S' in 'species')
## Warning: Removed 2 rows containing non-finite values (stat_boxplot).


themes

Themes allow us to change the background color and most other aspects of a plot. There are a range of theme options within ggplot that will allow us to quickly make clean plots. The two that are most commonly used are theme_bw() and theme_classic()

Default theme (with terrible gray background)

ggplot(data=penguins, aes(x=species, y= bill_length_mm)) +
  geom_boxplot(aes(fill=species))+
  scale_fill_aaas()+
  labs(x = 'Species', y='Bill length (mm)', title='Penguin bill length by species')
## Warning: Removed 2 rows containing non-finite values (stat_boxplot).

theme_bw() (removes gray background)

ggplot(data=penguins, aes(x=species, y= bill_length_mm)) +
  geom_boxplot(aes(fill=species))+
  scale_fill_aaas()+
  labs(x = 'Species', y='Bill length (mm)', title='Penguin bill length by species')+
  theme_bw()
## Warning: Removed 2 rows containing non-finite values (stat_boxplot).

theme_classic() (removes gray and grid lines)

ggplot(data=penguins, aes(x=species, y= bill_length_mm)) +
  geom_boxplot(aes(fill=species))+
  scale_fill_aaas()+
  labs(x = 'Species', y='Bill length (mm)', title='Penguin bill length by species')+
  theme_classic()
## Warning: Removed 2 rows containing non-finite values (stat_boxplot).

The theme() function in ggplot is SUPER flexible. You can pretty much do anything with it. This is key for customizing plots. I’d encourage you to play around with this a bit. Here is a great place to learn more and see examples.


facets

Facets allow us to produce multiple graph panels with one ggplot code. We can separate out a variable for easier viewing or even create a grid of graphs using multiple variables.

facet_wrap() allows us to make multiple panels. The panels are aligned in columns and rows. We need to use ‘~’ in our facet_wrap code. The ‘~’ essentially means “by”

ggplot(data=penguins, aes(x=sex, y= bill_length_mm, fill=species)) +
  geom_boxplot()+
  facet_wrap(~island)+
  scale_color_aaas()+
  theme_classic()
## Warning: Removed 2 rows containing non-finite values (stat_boxplot).

We can specify the number of columns and rows we want to built the panels how we like them

ggplot(data=penguins, aes(x=sex, y= bill_length_mm, fill=species)) +
  geom_boxplot()+
  facet_wrap(~island, ncol=2)+ #2 columns 
  scale_color_aaas()+
  theme_classic()
## Warning: Removed 2 rows containing non-finite values (stat_boxplot).

ggplot(data=penguins, aes(x=sex, y= bill_length_mm, fill=species)) +
  geom_boxplot()+
  facet_wrap(~island, nrow=3)+ #3 rows
  scale_color_aaas()+
  theme_classic()
## Warning: Removed 2 rows containing non-finite values (stat_boxplot).

We can even use a formula for building our facets if we’d like!

ggplot(data=penguins, aes(x=island, y= bill_length_mm, fill=species)) +
  geom_boxplot()+
  facet_wrap(~species+sex)+
  scale_color_aaas()+
  theme_classic()
## Warning: Removed 2 rows containing non-finite values (stat_boxplot).


Multiple plots on the same page

Using the simple and wonderful patchwork package, we can place multiple plots on the same page. To do this, we must actually name each plot. Here’s an example.

Patchwork is super easy! Learn more here(with examples)

First, let’s make some graphs and name them

p1<-ggplot(data=penguins, aes(bill_length_mm))+
  geom_histogram()+
  theme_classic()


p2<-ggplot()+
  geom_jitter(data= penguins, aes(x=species, y=bill_length_mm, color=sex), alpha=0.5, width=0.2)+
  geom_point(data=sumpens, aes(x=species, y=meanbill, color=sex), size=3)+
  geom_errorbar(data=sumpens, aes(x=species, ymin=meanbill-se, ymax=meanbill+se), width=0.1)+
  theme_classic()+
  scale_color_aaas()

p3<-ggplot(data=penguins, aes(sex)) +
  geom_bar(aes(fill=species), position= position_dodge())+
  theme_classic()+
  scale_fill_aaas()

Now let’s patchwork them together! We make a simple formula to make a patchwork. Addition puts everything in the same row. But we can use division and other symbols to organize.

library(patchwork)

p1+p2+p3
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 2 rows containing non-finite values (stat_bin).
## Warning: Removed 11 rows containing missing values (geom_point).

Division allows us to put panels in columns

p1/p2/p3
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 2 rows containing non-finite values (stat_bin).
## Warning: Removed 11 rows containing missing values (geom_point).

We can also combine addition and division (order of operations is still a thing!)

(p1+p2) / p3
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 2 rows containing non-finite values (stat_bin).
## Warning: Removed 11 rows containing missing values (geom_point).

There are other functions in patchwork that allow us to annotate plots, give them labels, move/combine legends, etc.


4.) Applying what we’ve learned

1.) Grab some data and make a boxplot, bar plot, histogram, and scatter plot 2.) Calculate a mean and plot mean + error 3.) Try facets, changing shapes, sizes, and customizing colors and themes.